package com.example.smsservice;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import com.example.smsservice.testurl.MyTask;

import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class validateServiceActivity  extends Activity {

	ListView mListData;
	TextView ttt;
	 final String textSource = "http://192.168.43.123/nim.cgi?rl=o";
	//private static final String TAG  = "DatabaseHelper";
		
	public static final String  DATABASE_FILE_PATH = "/sdcard";
	//public static final String  DATABASE_FILE_PATH =Environment.getExternalStorageDirectory().getPath();
	public static final String  DATABASE_NAME = "Indus_Database.sqlite";
		private static final String TRACKS_TABLE_CREATE =
			"create table if not exists Indus_TKTMst (TKTid integer primary key autoincrement, NOC_TKT_ID int, SE_ID int null, MAC varchar(50) null,IMEI varchar(50) null,Date_OfCreation date default CURRENT_DATE, Completion_Status varchar(10) null);";
		private SQLiteDatabase database;
		
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.vmain);

	        mListData = (ListView)findViewById(R.id.vlvData);
	        // receive list incoming messages
	        ArrayList<SmsInfo> listSms = getIntent().getParcelableArrayListExtra("ListSMS");
	        // check condition
	        if(listSms != null && listSms.size() > 0) {
	        	// set dat to list
	        	SmsInfoAdapter adapter = new SmsInfoAdapter(this, listSms);
		        mListData.setAdapter(adapter);
		        
		      try
		        {
		        database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FILE_PATH + File.separator + DATABASE_NAME, null);
				//createTables();
		        
		        database.execSQL(TRACKS_TABLE_CREATE);
				
				String param1="";
			      String param2="";
			      String param3="";
			      String param4="";
			      String param5="";
			      String param6="";
			     
			      Bundle bundle = this.getIntent().getExtras();
				  param1 = bundle.getString("TKTid");
				  param2 = bundle.getString("NOC_TKT_ID");
				  param3 = bundle.getString("Completion_Status");
				  param4 = bundle.getString("IMEI");
				  param5 = bundle.getString("wmac");
				  param6 = bundle.getString("SID");
			      //param1 = "9";
			      //  param2 = "9";
			      //  param3 = "Pending";
					
				 // Toast.makeText( getBaseContext(), param1, Toast.LENGTH_SHORT ).show();
				 // Toast.makeText( getBaseContext(), param2, Toast.LENGTH_SHORT ).show();
				 // Toast.makeText( getBaseContext(), param3, Toast.LENGTH_SHORT ).show();
				  
				  Cursor c1 = database.rawQuery("SELECT * FROM Indus_TKTMst where NOC_TKT_ID="+param2+"" , null);
				  int NOC_TKT_IDCOL1  = c1.getColumnIndex("NOC_TKT_ID");
				  c1.moveToFirst();
				  Toast.makeText( getBaseContext(), "Count: "+c1.getCount(), Toast.LENGTH_SHORT ).show(); 
	              if (c1.getCount()>0) {
		                if (c1.isFirst()) {
		                	
		                	 //database.execSQL("INSERT INTO Indus_TKTMst(TKTid, NOC_TKT_ID, Completion_Status) VALUES ("+param1+","+param2+", 'Pending')");
		                	 database.execSQL("UPDATE Indus_TKTMst set SE_ID="+param6+" , IMEI = '"+ param4+"' , MAC ='"+param5+"',Completion_Status='Accept' where NOC_TKT_ID="+param2+"");
		                	 c1.close();
		                	 new MyTask().execute();
		 					
								
							 
		                }
	                }
	              else
	              {
			      
	            	  database.execSQL("INSERT INTO Indus_TKTMst(TKTid, NOC_TKT_ID, Completion_Status) VALUES ("+param1+","+param2+", 'Pending')");
	            	  c1.close();
	            	  new MyTask().execute();
			     
	              }
				
				  Cursor c = database.rawQuery("SELECT * FROM Indus_TKTMst" , null);
		           int  TKT_IDCOL  = c.getColumnIndex("TKTid");             
		           int NOC_TKT_IDCOL  = c.getColumnIndex("NOC_TKT_ID");
		           int MACCOL  = c.getColumnIndex("MAC");
		           int IMEICOL  = c.getColumnIndex("IMEI");
		              
		              c.moveToFirst();
		           
		              if (c != null) {
		                if (c.isFirst()) {
		                       int i = 0;
		                    
		                       do {
		                            i++;
		                        
		                         String   TID = c.getString(TKT_IDCOL);
		                         String TKTID = c.getString(NOC_TKT_IDCOL);
		                         String MAC= c.getString(MACCOL);
		                         String IMEI= c.getString(IMEICOL);
		                         Toast.makeText( getBaseContext(), TKTID, Toast.LENGTH_SHORT ).show();
		                          
		                         //   print(TID+ " - " +TKTID);
		                       } while(c.moveToNext());
		                    }
		                c.close();
		              }
		      database.close();
		        }
		      catch(SQLException ex)
		      {
		    	  Toast.makeText( getBaseContext(), ex.getMessage().toString(), Toast.LENGTH_SHORT ).show();
		      }
		       
	        }
	    }


		 public class MyTask extends AsyncTask<Void, Void, Void>{
			   
			   String textResult;
			   
			   @Override
			   protected Void doInBackground(Void... params) {
				   
			       URL textUrl;

			       try {
			    	   textUrl = new URL(textSource);

			    	   BufferedReader bufferReader 
			    	   	= new BufferedReader(new InputStreamReader(textUrl.openStream()));
			    	   
			    	   String StringBuffer;
			    	   String stringText = "";
			    	   while ((StringBuffer = bufferReader.readLine()) != null) {
			    		   stringText += StringBuffer;   
			    	   }
			    	   bufferReader.close();

			    	   textResult = stringText;
			       } catch (MalformedURLException e) {
			    	   // TODO Auto-generated catch block
			    	   e.printStackTrace();
			    	   textResult = e.toString();   
			       } catch (IOException e) {
			    	   // TODO Auto-generated catch block
			    	   e.printStackTrace();
			    	   textResult = e.toString();   
			       }

				   return null;
				   
			   }
			   
			   @Override
			   protected void onPostExecute(Void result) {
				   
				  
				   
				   super.onPostExecute(result);   
			   }

		   }

}
